#ifndef PORTMACRO_H
#define PORTMACRO_H

#ifdef __cplusplus
    extern "C" {
#endif
#include "riscv/riscv_core.h"
#include "core/include/hpm6e00_regs_csr.h"

/* \brief 类型定义 */
#if __riscv_xlen == 64
    #define portSTACK_TYPE           uint64_t
    #define portBASE_TYPE            int64_t
    #define portUBASE_TYPE           uint64_t
    #define portMAX_DELAY           (TickType_t) 0xffffffffffffffffUL
    #define portPOINTER_SIZE_TYPE    uint64_t
#elif __riscv_xlen == 32
    #define portSTACK_TYPE           uint32_t
    #define portBASE_TYPE            int32_t
    #define portUBASE_TYPE           uint32_t
    #define portMAX_DELAY           (TickType_t) 0xffffffffUL
#else /* if __riscv_xlen == 64 */
    #error "Assembler did not define __riscv_xlen"
#endif /* if __riscv_xlen == 64 */

typedef portSTACK_TYPE   StackType_t;
typedef portBASE_TYPE    BaseType_t;
typedef portUBASE_TYPE   UBaseType_t;
typedef portUBASE_TYPE   TickType_t;

#ifdef __riscv_32e
    #define portBYTE_ALIGNMENT    8     /* RV32E 采用 RISC-V EABI（嵌入式应用二进制接口），并降低了栈对齐要求 */
#else
    #define portBYTE_ALIGNMENT    16
#endif

/* \brief 架构特定 */
#define portSTACK_GROWTH         (-1)   /* 栈向下增长 */

/* \brief 调度器组件 */
extern void vTaskSwitchContext(void);

/* \brief 触发任务切换
 *        ecall 指令用于触发 trap 处理程序 */
#define portYIELD()                __asm volatile("ecall");

#define portEND_SWITCHING_ISR(xSwitchRequired)   \
    do {                                         \
        if (xSwitchRequired != pdFALSE) {        \
            traceISR_EXIT_TO_SCHEDULER();        \
            vTaskSwitchContext();                \
        } else {                                 \
            traceISR_EXIT();                     \
        }                                        \
    } while(0)
#define portYIELD_FROM_ISR(x)    portEND_SWITCHING_ISR(x)

/* \brief 临界区管理 */
#define portCRITICAL_NESTING_IN_TCB    0

/* \brief 关闭中断 */
#define portDISABLE_INTERRUPTS()         clear_csr(CSR_MSTATUS, CSR_MSTATUS_MIE_MASK)
/* \brief 使能中断 */
#define portENABLE_INTERRUPTS()          set_csr(CSR_MSTATUS, CSR_MSTATUS_MIE_MASK)

/* \brief 临界区嵌套计数 */
extern size_t xCriticalNesting;
/* \brief 进入临界区 */
#define portENTER_CRITICAL() {       \
        portDISABLE_INTERRUPTS();    \
        xCriticalNesting++;          \
    }

/* \brief 退出临界区 */
#define portEXIT_CRITICAL() {          \
        xCriticalNesting--;            \
        if (xCriticalNesting == 0) {   \
            portENABLE_INTERRUPTS();   \
        }                              \
    }

/* \brief 本移植版本无需使用这些宏，其定义仅为确保通用演示文件（需适配所有移植版本）能够正常编译 */
#define portTASK_FUNCTION_PROTO(vFunction, pvParameters)    void vFunction(void * pvParameters)
#define portTASK_FUNCTION(vFunction, pvParameters)          void vFunction(void * pvParameters)

#endif
